<?php
/**
 * CategoryService.class.php 
 * Created Time 2016年4月9日 上午12:21:05
 *
 * @author     late.xiao@qq.com
 */

namespace Home\Service;

use Home\Common\Service;

class CategoryService extends Service {
    
    protected $catMdl;
    protected $cnameLength = array('min'=>1, 'max'=>8);
    public function __construct()
    {
        parent::__construct();
        $this->catMdl = M('Category');
    }
    
    /**
     * 删除一条数据
     * @param int $cid
     * @return bool
     * */
    public function delRow($cid)
    {
        $cid = intval($cid);
        // 查看删除的数据是否存在
        $data = $this->getCatRow($cid, 'cid');
        $rs = false;
        if($data)
        {
            // 查看此分类下是否有子类
            $result = $this->catMdl->where('pid=%d', $cid)->field('cid')->select();
            if($result)
            {
                throw new \Exception(L('_ERR_CAT_DEL'));
            }
            $rs = $this->catMdl->where('cid=%d', $cid)->delete();
        }

        if(!$rs)
        {
            throw new \Exception(L('_ERR_DEL_'));
        }
        
        return $rs;
    }
    /**
     * 获取分类列表
     * 
     * @param string $field
     * @param bool $isParent true只取一级分类，false取所有的分类
     * @return array
     * */
    public function getCatList($field="*", $filter = array(), $isParent=false)
    {
        $data = array();
        if($isParent)
        {
            $this->catMdl->where('pid=%d', 0);
        }
        if($filter && is_array($filter))
        {
            $this->catMdl->where($filter);
        }
        
        $data = $this->catMdl->field($field)->select();
        
        return $data;
    }
    
    public function getCatRow($cid, $field='*')
    {
        $data = array();
        $data = $this->catMdl->where('cid=%d', intval($cid))->field($field)->find();
        if(!$data)
        {
            throw new \Exception(L('_ERR_EMPTY_CATEGORY_'));
        }
        
        return $data;
    }
    
    /**
     * 保存数据
     * @param array $request 获取到的数据
     * @return int 
     * */
    public function saveData($request, &$cid)
    {
        // 验证数据
        $this->__checkData($request);
        
        // 处理入库数据
        $saveData = array();
        $saveData['sort'] = intval($request['sort']);
        $saveData['pid'] = intval($request['pid']);
        $saveData['cname'] = $request['cname'];
        $saveData['updated'] = NOW_TIME;
        // 开始入库
        try {
            if(isset($request['cid']) && $cid = intval($request['cid']))
            {
                $rs = $this->catMdl->where('cid=%d', $cid)->save($saveData);
            }
            else
            {
                $saveData['created'] = $saveData['updated'];
                $rs = $cid = $this->catMdl->add($saveData);
            }
            
            if(!$rs)
            {
                throw new \Exception(L('_ERR_SAVE_'));
            }
        } catch (\Exception $e) {
            throw $e;
        }
        
        return $rs;
    }
    
    public function proCatList($data)
    {
        if(!is_array($data) || !$data)
        {
            return false;
        }
        
        // 获取所有的父类
        $pcatList = array();
        foreach ($data as $v)
        {
            if($v['pid'] == 0)
            {
                $pcatList[$v['cid']] = $v;
            }
        }
        // 组合数据
        foreach ($data as $v)
        {
            if(array_key_exists($v['pid'], $pcatList))
            {
                $pcatList[$v['pid']]['child'][] = $v;
            }
        }
        
        return $pcatList;
    }
    
    private function __checkData($data)
    {
        $errors = array();
        $options = array(
                'cname' =>array(
                        'required' => array(
                            'rule'=>true,
                            'message'=>L('_ERR_EMPTY_CNAME_')
                        ),
                        'string_count_in_range' => array(
                                'rule'=>array_values($this->cnameLength),
                                'message'=>L('_ERR_LENGTH_CNAME_', $this->cnameLength)
                        ),
                        
                ),
        );
        
        $rs = \Base\Lib\Tools\Validator::make($errors, $data, $options);
        if(!$rs)
        {
            foreach ($errors as $k=>$v)
            {
                throw new \Exception($v);
            }
        }
        
        if($data['sort'])
        {
            if(!$rs = is_numeric($data['sort']))
            {
                throw new \Exception(L('_ERR_FORMART_PARAMS_NUM',array('param' => 'sort')));
            }
        }
        
        if($data['pid'])
        {
            if(!$rs = is_numeric($data['pid']))
            {
                throw new \Exception(L('_ERR_FORMART_PARAMS_NUM',array('param' => 'pid')));
            }
        }
        
        return $rs;
    }
}
 
 